package com.cy.ppj.service.account.impl;

import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.comm.utils.JsonObjectMapper;
import com.cy.ppj.dao.mongodb.CertificationInfoDao;
import com.cy.ppj.model.Result;
import com.cy.ppj.model.doc.CertificationInfo;
import com.cy.ppj.model.domian.user.UserInfo;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.account.CertificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 实名认证
 * @author: Ocean
 * @create: 2018-09-12 13:59
 **/
@Slf4j
@Service
public class CertificationServiceImpl extends BaseService implements CertificationService {

    private final String url = "https://idcardcert.market.alicloudapi.com/idCardCert?idCard={idCard}&name={name}";

    @Value("${aliyun.id-card-cert.app-code}")
    private String appCode;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private CertificationInfoDao certificationInfoDao;

    private HttpEntity httpEntity;

    @PostConstruct
    public void initHeaders() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "APPCODE " + appCode);
        httpEntity = new HttpEntity(null, httpHeaders);
    }

    @Override
    @Transactional
    public Result<UserInfo> certification(String name, String idCard) {
    	//查询mangoDB，若存在则直接返回验证成功
        CertificationInfo dbCertificationInfo = queryCertificationInfo(idCard);
        if (dbCertificationInfo != null) {
            UserInfo userInfo = new UserInfo();
            userInfo.setIdNo(dbCertificationInfo.getIdCard());
            userInfo.setRealName(dbCertificationInfo.getName());
            return Result.success("实名认证通过！", userInfo);
        }
        //调用验证api进行实名验证
        Result<Map<String, String>> result = httpGetToCertification(name, idCard);
        if(!result.isOk()) {
        	return Result.fail(result.getMessage());
        }
        
        //得到验证之后的 姓名和身份证号码
        Map<String, String> certificationResultMap = result.getValue();
        name = certificationResultMap.get("name");
        idCard = certificationResultMap.get("idCard");
        
        //封装数据，返回
        UserInfo userInfo = new UserInfo();
        userInfo.setIdNo(idCard);
        userInfo.setRealName(name);

        return Result.success("实名认证通过！", userInfo);
    }

    @Override
    public CertificationInfo queryCertificationInfo(String idCard) {
        return certificationInfoDao.findByIdCard(idCard);
    }

	@Override
	public Result<Map<String, String>> certificationIdCard(String name, String idCard) {
		Map<String, String> resultMap = new HashMap<>();
		//查询mangoDB，若存在则直接返回验证成功
		CertificationInfo dbCertificationInfo = queryCertificationInfo(idCard);
		if(!CommonUtils.isEmpty(dbCertificationInfo)) {
			resultMap.put("name", dbCertificationInfo.getName());
			resultMap.put("idCard", dbCertificationInfo.getIdCard());
			return Result.success("实名认证通过！", resultMap);
		}
		
		//调用验证api进行实名验证
        Result<Map<String, String>> result = httpGetToCertification(name, idCard);
		
		return result;
	}
	
	/**
	 * 调用验证api进行实名验证
	 * 
	 * @param name
	 * @param idCard
	 * @return
	 */
	private Result<Map<String, String>> httpGetToCertification(String name, String idCard) {
		
		//调用验证api进行实名验证
		Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("idCard", idCard);

        log.info("实名验证请求参数: {}", params);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, params);
        if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
        	return Result.fail("实名认证请求失败");
        }

        log.info("实名验证回调参数: {}", responseEntity.getBody());

        Map<String, Object> map = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
        String status = map.get("status").toString();
        if (!"01".equals(status)) {
        	return Result.fail("实名认证失败，msg = " + map.get("msg"));
        }

        //得到验证之后的 姓名和身份证号码
        name = map.get("name").toString();
        idCard = map.get("idCard").toString();
        
        //保存记录到MongoDB
        CertificationInfo certificationInfo = new CertificationInfo();
        certificationInfo.setIdCard(idCard);
        certificationInfo.setName(name);
        certificationInfo.setData(responseEntity.getBody());
        certificationInfo.setCreateTime(new Date());
        certificationInfoDao.insert(certificationInfo);
        
        Map<String, String> resultMap = new HashMap<>();;
        resultMap.put("name", name);
        resultMap.put("idCard", idCard);
        
        return Result.success("实名认证通过！", resultMap);
	}
}
